#include <53func.h>
int main(int argc, char *argv[])
{
    // ./10_azhen_select 1.pipe 2.pipe 
    ARGS_CHECK(argc,3);
    int fdw = open(argv[1],O_WRONLY);
    int fdr = open(argv[2],O_RDONLY);
    printf("azhen is ready!\n");
    char buf[4096] = {0};
    ssize_t sret;
    // 1 为fd_set 申请内存
    fd_set rdset; // 目前的资源都是读阻塞
    while(1){
        // 2 初始化集合
        FD_ZERO(&rdset);
        // 3 设置好监听
        // 如果是循环配合select的话，每次select之前要重新设置监听集合
        FD_SET(STDIN_FILENO,&rdset); // 把标准输入加入监听
        FD_SET(fdr, &rdset); // 把管道的读端加入监听
        struct timeval timeout;
        timeout.tv_sec = 3;
        timeout.tv_usec = 0;
        // 4 调用select 进程阻塞，内核轮询
        int ret = select(fdr+1,&rdset,NULL,NULL,&timeout);
        if(ret == 0){
            printf("timeout !\n");
            continue;
        }
        // 从select中返回，说明了 stdin 或者 fdr就绪
        if(FD_ISSET(STDIN_FILENO,&rdset)){
            // stdin就绪
            memset(buf,0,sizeof(buf));
            sret = read(STDIN_FILENO,buf,sizeof(buf));
            if(sret == 0){
                write(fdw,"nishigehaoren",13);
                break;
            }
            write(fdw,buf,strlen(buf));
        }
        if(FD_ISSET(fdr,&rdset)){
            // fdr就绪
            memset(buf,0,sizeof(buf));
            sret = read(fdr,buf,sizeof(buf));
            if(sret == 0){
                printf("Hehe!\n");
                break;
            }
            printf("buf = %s\n", buf);
        }
    }
    close(fdr);
    close(fdw);
    return 0;
}

